#K个一组反转链表
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        dummy = ListNode(0)
        dummy.next = head
        prev = dummy

        while True:
            # 检查剩余节点是否足够k个
            tail = prev
            for _ in range(k):
                tail = tail.next
                if not tail:
                    return dummy.next
            next_head = tail.next  # 下一组的头节点

            # 翻转当前k个节点
            current = prev.next
            prev_node = None
            for _ in range(k):
                next_node = current.next
                current.next = prev_node
                prev_node = current
                current = next_node

            # 将翻转后的子链表连接回去
            start = prev.next  # 翻转后的尾节点
            prev.next = prev_node  # 连接前一部分到翻转后的头节点
            start.next = next_head  # 翻转后的尾节点连接到下一组的头节点

            # 更新prev到当前组的尾节点
            prev = start


def create_linked_list(lst):
    """将列表转换为链表"""
    dummy = ListNode(0)
    current = dummy
    for num in lst:
        current.next = ListNode(num)
        current = current.next
    return dummy.next


def linked_list_to_list(head):
    """将链表转换为列表"""
    result = []
    while head:
        result.append(head.val)
        head = head.next
    return result


if __name__ == "__main__":
    # 测试用例1
    head1 = create_linked_list([1, 2, 3, 4, 5])
    result1 = Solution().reverseKGroup(head1, 2)
    print(linked_list_to_list(result1))  # 输出: [2, 1, 4, 3, 5]

    # 测试用例2
    head2 = create_linked_list([1, 2, 3, 4, 5])
    result2 = Solution().reverseKGroup(head2, 3)
    print(linked_list_to_list(result2))  # 输出: [3, 2, 1, 4, 5]